package com.sky.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author moningxi
 */
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 保存数据到 Redis
    public void saveString(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 保存并设置过期时间
     */
    public void saveString(String key, Object value, int second) {
        redisTemplate.opsForValue().set(key, value, second);
    }

    // 从 Redis 获取数据
    public Object getString(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除 Redis 中的数据
    public void deleteString(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(Set<String> keys) {
        redisTemplate.delete(keys);
    }

    /**
     * 查询所有的key
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 数量自增 用于限流
     */
    public int add(String key, int timeout) {
        // 尝试设置键的初始值并设置过期时间
        boolean isSet = Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, 1, timeout, TimeUnit.SECONDS));

        if (!isSet) {
            // 如果键已经存在，执行自增操作
            redisTemplate.opsForValue().increment(key);
        }
        Integer value = (Integer) redisTemplate.opsForValue().get(key);
        int count = (value != null) ? value : 0;
        return count;
    }
}